<template>
  <view>
    <view class="header"> </view>
    <view class="layout">
      <view class="content">
        <!-- <image class="priviewImg" :src="'data:image/png;base64,' + priviewSrc" mode=""></image> -->
        <div
          class="priviewImg"
          :style="{ backgroundImage: `url(data:image/png;base64,${priviewSrc})` }"
        >
        </div>
        <view class="example_box">
          <view class="example_img" v-for="(item, index) in exampleList" :key="index">
            <uni-card
              id="example_card"
              padding="0"
              spacing="0"
              margin="0"
              style="width: 100%; height: 100%"
              @tap="switchImg(item)"
            >
              <image
                :src="'data:image/png;base64,' + item"
                mode="scaleToFill"
                style="width: 100%; height: 75px"
              >
              </image>
              <view
                class=""
                style="height: 25rpx; width: 100%; line-height: 18rpx; overflow: hidden"
              >
                <text style="font-weight: bold; font-size: 10px">{{ keyWordName }}</text>
              </view>
            </uni-card>
          </view>
        </view>
        <view class="generate">
          <view class="generate_int">
            <textarea v-model="keyword" :placeholder="$t('generate.inputPrompt')" />
          </view>
        </view>
        <view class="button_box">
          <view class="againRefresh" @tap="refresh">
            <uni-icons type="refreshempty" size="20"></uni-icons>
            <text>{{ $t('generate.regenerate') }}</text>
          </view>
          <view
            class="againRefresh"
            style="background-color: #f9e056; color: #83320d"
            @tap="startPrint"
          >
            <text>{{ $t('generate.confirmPrint') }}</text>
          </view>
        </view>
      </view>
    </view>
    <su-popup :show="iskeyWord" type="center" @close="closeKeyWord">
      <view class="uni-dialog-title">
        <text class="uni-dialog-title-text uni-popup__warn">
          {{ $t('generate.emptyPromptWarning') }}
        </text>
      </view>
    </su-popup>
    <su-popup :show="progressShow" type="center" background-color="" @close="closeProgressDialog">
      <view class="progress_content">
        <progressLine :pgList="progressData"></progressLine>
      </view>
    </su-popup>
  </view>
</template>

<script>
  import sheep from '@/sheep';
  import progressLine from './components/progress.vue';
  import { onLoad } from '@dcloudio/uni-app';
  import GenerateApi from '@/sheep/api/generate/aiGenerate';
  import { useI18n } from 'vue-i18n';

  export default {
    components: {
      progressLine,
    },
    setup() {
      const { t } = useI18n();
      return { t };
    },
    data() {
      return {
        keyword: '',
        keyWordName: '',
        exampleList: [],
        priviewSrc: '',
        iskeyWord: false,
        progressData: {
          num: 100,
          duration: 75,
        },
        progressShow: false,
      };
    },
    onLoad() {
      this.keyword = uni.getStorageSync('printName');
      this.keyWordName = uni.getStorageSync('printName');
      // this.keyword = this.$route.query.keyWord;
      // this.getImgPriview();
      this.exampleList = uni.getStorageSync('imgList');
      this.exampleList.forEach((item, index) => {
        this.convertToColor(item, index);
      });
    },
    methods: {
      async getImgPriview() {
        this.progressShow = true;
        const { code, data } = await GenerateApi.getWordGenerate({
          keyword: this.keyword,
        });
        if (code == 0) {
          this.progressShow = false;
          this.keyWordName = this.keyword;
          this.exampleList = data.images;
          uni.setStorageSync('imgList', data.images);
          uni.setStorageSync('printName', this.keyword);
          this.exampleList.forEach((item, index) => {
            this.convertToColor(item, index);
          });
          this.priviewSrc = data.images[0];
        } else {
          this.progressShow = false;
        }
      },
      refresh() {
        if (this.keyword == '') {
          this.iskeyWord = true;
        } else {
          this.getImgPriview();
        }
      },
      switchImg(val) {
        this.priviewSrc = val;
      },
      startPrint() {
        // console.log(this.keyword, '556')
        uni.setStorageSync('printSrc', this.priviewSrc);
        uni.setStorageSync('printName', this.keyword);
        sheep.$router.go('/pages/generate/print');
      },
      convertToColor(dataUrl, index) {
        const image = new Image();
        image.src = 'data:image/png;base64,' + dataUrl;
        image.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = image.width;
          canvas.height = image.height;
          ctx.drawImage(image, 0, 0);

          // 获取图像数据
          const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
          const data = imageData.data;

          // 定义要替换的颜色 (107, 48, 13)
          const targetColor = {
            r: 241,
            g: 186,
            b: 63,
          };

          // 遍历像素并修改颜色
          for (let i = 0; i < data.length; i += 4) {
            // 检查是否是黑色（RGB值接近0的像素）
            if (data[i] < 200 && data[i + 1] < 200 && data[i + 2] < 200) {
              data[i] = targetColor.r; // 红色通道设置为 107
              data[i + 1] = targetColor.g; // 绿色通道设置为 48
              data[i + 2] = targetColor.b; // 蓝色通道设置为 13
            }
          }
          // 将处理后的数据重新绘制到画布上
          ctx.putImageData(imageData, 0, 0);
          // console.log(canvas.toDataURL('image/png').split(',')[1],'ppp')
          // 更新预览图片源
          this.exampleList[index] = canvas.toDataURL('image/png').split(',')[1];
          this.priviewSrc = this.exampleList[0];
        };
      },
      closeKeyWord() {
        this.$emit('close');
        this.iskeyWord = false;
      },
      closeProgressDialog() {
        this.$emit('close');
        this.progressShow = false;
      },
    },
  };
</script>

<style lang="scss" scoped>
  .header {
    width: 100%;
    height: 150px;
    background-image: url('../../static/header.gif');
    background-repeat: no-repeat;
    background-size: cover;
  }

  .layout {
    width: 90%;
    height: 100%;
    margin: -72px auto;
    display: flex;
    justify-content: center;
  }

  .content {
    width: 90%;
    height: 100%;
    background-color: #fff;
    padding: 15px;
    border-radius: 10px;

    .priviewImg {
      width: 100%;
      height: 350px;
      border-radius: 10px;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center;
    }

    .example_box {
      margin-top: 20rpx;
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .example_img {
        width: 20%;
        margin: 20rpx 10rpx;
      }
    }

    .generate {
      width: 100%;
      // height: 100px;

      // display: flex;
      // justify-content: space-between;
      .generate_int {
        height: 100px;
        padding: 10px;
        border-radius: 10px;
        background-color: #f3f3f3;
      }
    }
  }

  .button_box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-top: 15px;

    .againRefresh {
      width: 45%;
      height: 50px;
      background-color: #f3f3f3;
      color: #000;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 10px;
    }
  }

  .progress_content {
    width: calc(100vw - 80px);
    height: 50px;
    margin: 0 auto;
  }

  .uni-dialog-title {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    border-radius: 10px;
    flex-direction: row;
    justify-content: center;
    padding: 20px; // padding-top: 25px;
  }

  .uni-dialog-title-text {
    font-size: 16px;
    font-weight: 500;
    color: #83320d;
  }

  :deep(#example_card) {
    border-radius: 30rpx;
  }

  :deep(#example_card .uni-card__content) {
    width: 100%;
    height: 100%;
    text-align: center;
  }

  :deep(uni-textarea) {
    width: 100%;
    height: 100%;
  }

  :deep(.uni-textarea-wrapper) {
    background-color: #f3f3f3;
    color: #666;
  }
</style>
